﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Foundry.Graphics
{
    public interface IHandle : IDisposable
    {
        bool Disposed { get; }
        event EventHandler Disposing;
        int Handle { get; }
        void MakeCurrent();
        void MakeNullCurrent();
    }

    internal static class Module
    {
        static Dictionary<OpenTK.Graphics.IGraphicsContext, List<IHandle>> object_pool = new Dictionary<IGraphicsContext, List<IHandle>>();

        internal static void Register(IHandle @object)
        {
            if (object_pool[GraphicsContext.CurrentContext] == null)
                object_pool[GraphicsContext.CurrentContext] = new List<IHandle>();
            object_pool[GraphicsContext.CurrentContext].Add(@object);
        }

        internal static void UnregisterContext(IGraphicsContext context)
        {
            if (object_pool[context] != null)
            {
                foreach (var item in object_pool[context])
                {
                    if(!item.Disposed)
                        item.Dispose();
                }
                object_pool.Remove(context);
            }
        }

        internal static void Unregister(IHandle @object)
        {
            if (object_pool[GraphicsContext.CurrentContext] != null)
            {
                object_pool[GraphicsContext.CurrentContext].Remove(@object);
            }
        }

    }
}
